<template>
  <Card size="small" title="JSON序列化">
    <template #extra>
      <div class="btn-group" style="margin-right: -10px">
        <Button type="primary" @click.native="encodeJson"><RightOutlined /> 编码</Button>
        <Button @click.native="onCopyScript" :disabled="!json.output"><CopyFilled /> 复制结果</Button>
      </div>
    </template>
    <Row :gutter="10">
      <Col :span="12">
        <Input.TextArea v-model:value="json.input" @blur="formatJson" :rows="bodyHeight / 20.5"></Input.TextArea>
      </Col>
      <Col :span="12">
        <Input.TextArea v-model:value="json.output" :readonly="true" :rows="bodyHeight / 20.5"></Input.TextArea>
      </Col>
    </Row>
  </Card>
</template>
<script setup>
  import { useStore } from 'vuex';
  import { computed, reactive, inject } from 'vue';
  import { Card, Row, Col, Input, Button } from 'ant-design-vue';
  import { RightOutlined, CopyFilled } from '@ant-design/icons-vue';

  const $store = useStore();
  const $message = inject('$message');
  const $copyText = inject('$copyText');
  const json = reactive({ input: '', output: '' });

  const bodyHeight = computed(() => {
    return $store.state.area.content.height - 140;
  });

  function formatJson() {
    try {
      let orginal = this.json.input;

      if (orginal.startsWith('=')) {
        orginal = orginal.substr(1);
      }

      let json = JSON.stringify(JSON.parse(orginal), null, 2);

      json.input = json;
    } catch {}
  }

  function encodeJson() {
    let bodyData = json.input;

    bodyData = bodyData.replace(/&/g, '%26').replace(/\\/g, '%5C').replace(/\+/g, '%2B').replace(/>/g, '%3e').replace(/</g, '%3c').replace(/#/g, '%23').replace(/~/g, '%40');

    json.output = bodyData;
  }

  function onCopyScript() {
    $copyText(json.output).then(() => {
      $message.success('代码已复制！');
    });
  }
</script>
<style lang="less" scoped>
  .ant-row {
    display: flex;
    flex-flow: nowrap;
    align-items: center;
  }
</style>
